from datetime import datetime
from flask import Blueprint, flash, render_template, request, redirect, url_for, session
from exts import db
from models import Statementmodel, Addstatementformmodel, Usermodel, Whomodel
from decorators import login_required

bp = Blueprint("sm", __name__, url_prefix="/sm")


@bp.route("/add_statement", methods=['GET', 'POST'])
@login_required
def add_statement():
    user_id = session['userid']
    user = Usermodel.query.filter_by(id=user_id).first()
    add_statement_form = Addstatementformmodel()
    statements = Statementmodel.query.filter_by(stage='1')
    submitted_statements = Statementmodel.query.filter_by(stage='2')
    # 1.调用WTF的函数实现验证
    if add_statement_form.validate_on_submit():
        # 2.验证通过获取数据
        new_input_time = add_statement_form.input_time.data
        new_inputer = user.username
        new_jobnumber = add_statement_form.jobnumber.data
        new_name = add_statement_form.who.data
        new_amount = add_statement_form.amount.data
        new_reason = add_statement_form.reason.data
        try:
            new_statement = Statementmodel(inputer=new_inputer,
                                           input_time=new_input_time,
                                           jobnumber=new_jobnumber,
                                           name=new_name,
                                           amount=new_amount,
                                           reason=new_reason,
                                           status='已暂存',
                                           stage='1'
                                           )
            db.session.add(new_statement)
            db.session.commit()
            flash('操作成功')
        except Exception as e:
            print(e)
            flash('操作失败')
            db.session.rollback()
        # 6. 验证不通过就提示错误
    elif request.method == 'POST':
        flash('参数不全')

    return render_template("add_statement.html", user=user, statements=statements,
                           submitted_statements=submitted_statements,
                           add_statement_form=add_statement_form)


@bp.route("/insert", methods=['GET', 'POST'])
@login_required
def insert():
    user_id = session['userid']
    user = Usermodel.query.filter_by(id=user_id).first()
    my_statements = Statementmodel.query.filter_by(inputer=user.username)
    return render_template("insert.html", user=user, my_statements=my_statements)


@bp.route("/delete/<statement_id>", methods=['GET', 'POST'])
@login_required
def delete(statement_id):
    # 1. 查询数据库, 是否有该ID的结付单, 如果有就删除, 没有提示错误
    statement = Statementmodel.query.get(statement_id)

    # 2. 如果有就删除
    if statement:
        try:
            db.session.delete(statement)
            db.session.commit()
            flash('删除成功')
        except Exception as e:
            flash('删除出错')
            db.session.rollback()

    else:
        # 3. 没有提示错误
        flash('找不到这张现金支付说明')
    return redirect(url_for("sm.add_statement"))


# 提交结付单 --> 网页中提交-->点击需要发送结付单的ID给提交的路由 --> 路由需要接受参数
@bp.route("/submit/<statement_id>", methods=['GET', 'POST'])
@login_required
def submit(statement_id):
    # 1. 查询数据库, 是否有该ID的结付单, 如果有就提交 没有提示错误
    statement = Statementmodel.query.get(statement_id)
    who = Whomodel.query.get(statement.jobnumber)
    user_id = session['userid']
    user = Usermodel.query.filter_by(id=user_id).first()
    username = user.username
    if user.role == 'examiner':
        # 2. 如果有就提交
        if statement:
            if who.number_of_times < 3:
                try:
                    statement.status = '已同意'
                    statement.stage = '2'
                    who.number_of_times = who.number_of_times + 1
                    statement.submitter = username
                    statement.submit_time = datetime.today()
                    statement.approver = username
                    statement.approve_time = datetime.today()
                    db.session.commit()
                    flash('提交成功')
                except Exception as e:
                    flash('提交出错')
                    db.session.rollback()
            else:
                try:
                    statement.status = '待同意'
                    statement.stage = '2'
                    statement.submitter = username
                    statement.submit_time = datetime.today()
                    db.session.commit()
                    flash('该教师特殊原因非公务卡支付已达到3次，请审批！')
                except Exception as e:
                    flash('提交出错')
                    db.session.rollback()
        else:
            # 3. 没有就提示错误
            flash('找不到这张现金支付说明')
    else:
        flash('您无权增加单据')
    return redirect(url_for("sm.insert"))


@bp.route("/process", methods=['GET', 'POST'])
@login_required
def process():
    user_id = session['userid']
    user = Usermodel.query.filter_by(id=user_id).first()
    statements = Statementmodel.query.filter_by(status='待同意')
    if user.role == 'examiner':
        return render_template("process.html", statements=statements)
    else:
        return redirect(url_for("sm.insert"))


@bp.route("/process/<statement_id>", methods=['GET', 'POST'])
@login_required
def approve(statement_id):
    # 1. 查询数据库, 是否有该ID的结付单, 如果有就提交 没有提示错误
    statement = Statementmodel.query.get(statement_id)
    who = Whomodel.query.get(statement.jobnumber)
    user_id = session['userid']
    user = Usermodel.query.filter_by(id=user_id).first()
    username = user.username
    # 2. 如果有就提交
    if statement:
        try:
            statement.status = '已同意'
            who.number_of_times = who.number_of_times + 1
            statement.approver = username
            statement.approve_time = datetime.today()
            db.session.commit()
            flash('提交成功')
        except Exception as e:
            flash('提交出错')
            db.session.rollback()
    else:
        # 3. 没有就提示错误
        flash('找不到这张现金支付说明')
    return redirect(url_for("sm.process"))


@bp.route("/refuse/<statement_id>", methods=['GET', 'POST'])
@login_required
def refuse(statement_id):
    # 1. 查询数据库, 是否有该ID的结付单, 如果有就提交 没有提示错误
    statement = Statementmodel.query.get(statement_id)
    user_id = session['userid']
    user = Usermodel.query.filter_by(id=user_id).first()
    username = user.username
    # 2. 如果有就提交
    if statement:
        try:
            statement.status = '已退回'
            statement.stage = '1'
            statement.approver = username
            statement.approve_time = datetime.today()
            db.session.commit()
            flash('退回成功')
        except Exception as e:
            flash('退回出错')
            db.session.rollback()
    else:
        # 3. 没有就提示错误
        flash('找不到这张现金支付说明')
    return redirect(url_for("sm.process"))


@bp.route("/search", methods=['GET', 'POST'])
@login_required
def search():
    whos = Whomodel.query.all
    statements = Statementmodel.query.all()
    return render_template("search.html", statements=statements, whos=whos)


@bp.route("/search_teacher")
@login_required
def search_teacher():
    this_teacher_id = request.args.get("this_teacher_id")
    this_teacher = Whomodel.query.filter_by(teacher_id=this_teacher_id).first()
    return render_template("search.html", this_teacher=this_teacher)
